package com.cqupt.controller;

import com.cqupt.common.log.annotation.OperationLog;
import com.cqupt.pojo.ResponseMessage;
import com.cqupt.service.ItemService;
import com.cqupt.service.LLDService;
import com.cqupt.service.impl.LLDServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@Controller
@RequestMapping("updateMonitor")
@ResponseBody
public class ItemController {
    // 初始化监控项原型
    static {
        LLDService llds = new LLDServiceImpl();
        // 获得监控项原型
        List<Map<String, Object>> prototypeItem = llds.getItemPrototypeByTemp(LLDService.tempidListNoSNMP);
        // 剥离出itemid
        String[] prototypeItemids = new String[prototypeItem.size()];
        int i = 0;
        for (Map<String, Object> result : prototypeItem) {
            prototypeItemids[i++] = (String)result.get("itemid");
        }
        // 更新监控项原型discovery状态
        llds.updateItemPrototype(prototypeItemids,LLDService.itemidNeed);
        // 获得网络接口net.if原型
        List<Map<String, Object>> prototypeNetItem = llds.setDelayNetItemPrototypeByTemp(LLDService.templateidList);
        // 剥离出itemid
        String[] prototypeNetItemids = new String[prototypeNetItem.size()];
        int j = 0;
        for (Map<String, Object> result : prototypeNetItem) {
            prototypeNetItemids[j++] = (String)result.get("itemid");
        }
        // 更新监控项原型的延迟时间
        llds.updateNetItemPrototype(prototypeNetItemids);

    }
    @Autowired
    private ItemService itemService;
    /**
    * @Description //启用监控项
    * @Date 15:13 2020/11/30
    * @Param
    **/
    @OperationLog(level = "信息", object = "监控项", operationType = "启用")
    @RequestMapping("/enableMonitorItem")
    public ResponseMessage enableMonitorItem(@RequestParam(value = "itemid")String itemid,
                                             @RequestParam(value = "name")String name){
        ResponseMessage responseMessage = new ResponseMessage();
        boolean enableItemFlag = itemService.enableMontiorItem(itemid);
        /**
         * 参数组装
         */
        Map<String, Object> resultMap = new HashMap<String, Object>(){{
            put("enableItem",enableItemFlag);
        }};
        resultMap.put("log_objectName",name);
        if (enableItemFlag == true){
            responseMessage.setStatus(true);
            resultMap.put("log_description","启用"+name);
        }else{
            responseMessage.setErrorCode("");
        }
        responseMessage.setContent(resultMap);
        return responseMessage;
    }
    /**
    * @Description //禁用监控项
    * @Date 15:29 2020/11/30
    * @Param
    **/
    @OperationLog(level = "信息", object = "监控项", operationType = "禁用")
    @RequestMapping("/stopMonitorItem")
    public ResponseMessage stopMonitorItem(@RequestParam(value = "itemid")String itemid,
                                           @RequestParam(value = "name")String name){
        ResponseMessage responseMessage = new ResponseMessage();
        boolean stopItemFlag = itemService.stopMontiorItem(itemid);
        /**
         * 参数组装
         */
        Map<String, Object> resultMap = new HashMap<String, Object>() {{
            put("stopItemFlag", stopItemFlag);
        }};
        resultMap.put("log_objectName",name);
        if (stopItemFlag == true){
            responseMessage.setStatus(true);
            resultMap.put("log_description","禁用"+name);
        }else{
            responseMessage.setErrorCode("");
        }
        responseMessage.setContent(resultMap);
        return responseMessage;
    }
    /**
    * @Description //删除监控项
    * @Date 15:38 2020/11/30
    * @Param
    **/
    @OperationLog(level = "信息", object = "监控项", operationType = "删除")
    @RequestMapping("/deleteMonitorItem")
    public ResponseMessage deleteMonitorItem(@RequestBody Map<String,Object> params){
        ResponseMessage responseMessage = new ResponseMessage();
        /**
         * 获取前端传递参数
         */
        List<String> itemids = (List<String>)params.get("itemids");
        List<String> itemnames = (List<String>)params.get("itemnames");
        Map<String, Object> error = itemService.deleteMonitorItem(itemids);
        Map<String, Object> resMap = new HashMap<>();
        if (itemnames.size() == 1){
            resMap.put("log_objectName", itemnames.get(0));
        }else{
            resMap.put("log_objectName", itemnames.toString());
        }
        if((boolean)error.get("flag") == true){
            //删除成功
            responseMessage.setStatus(true);
            resMap.put("log_description", "");
        }else{
            //删除失败
            responseMessage.setStatus(false);
            responseMessage.setErrorCode("内置监控不允许删除!");
        }

        responseMessage.setContent(resMap);
        return responseMessage;
    }
    /**
    * @Description //根据主机id查找所有监控项的相关信息
    * @Date 10:45 2020/12/2
    * @Param
    **/
    @RequestMapping("/queryMonitorItemByHostid")
    public ResponseMessage queryItemByHostId(@RequestParam(value = "hostid")String hostid){
        ResponseMessage responseMessage = new ResponseMessage();
        /**
         * 获取指定主机的相关监控项
         */
        List<Map<String, Object>> itemNews = itemService.getAllItem(hostid);
        Map<String, Object> resultMap = new HashMap<String, Object>(){{
            put("itemNews",itemNews);
        }};
        resultMap.put("total",itemNews.size());
        responseMessage.setStatus(true);
        responseMessage.setContent(resultMap);
        return responseMessage;
    }
    /**
    * @Description //创建监控项
    * @Date 16:38 2020/11/30
    * @Param [params]
    **/
    @OperationLog(level = "信息", object = "监控项", operationType = "新增")
    @RequestMapping("/creatMonitorItem")
    public ResponseMessage creatMonitorItem(@RequestBody Map<String,Object> params){
        ResponseMessage responseMessage = new ResponseMessage();
        Integer type = Integer.parseInt(params.get("type").toString());
        Integer value_type = (Integer)params.get("value_type");
        Map<String, Object> allNewsForItem = null;
        String key = params.get("key_").toString();
        Map<String,Object> createFlag = new HashMap<>();

        if (key.contains("log")){//日志类型监控项
            allNewsForItem = new HashMap<String,Object>(){{
                put("delay",params.get("delay").toString());
                put("hostid",params.get("hostid").toString());
                put("interfaceid",params.get("interfaceid").toString());
                put("key_",params.get("key_").toString());
                put("name",params.get("name").toString());
                put("type",7);
                put("value_type",2);
                put("description",params.get("description").toString());
                put("history",params.get("history").toString());
                put("trends",params.get("trends").toString());
            }};

            createFlag = itemService.creatMonitorItem(allNewsForItem,7);
        }else {
            //创建agent类型的监控项
            if (type == 0){
                allNewsForItem = new HashMap<String,Object>(){{
                    put("delay",params.get("delay").toString());
                    put("hostid",params.get("hostid").toString());
                    put("interfaceid",params.get("interfaceid").toString());
                    put("key_",params.get("key_").toString());
                    put("name",params.get("name").toString());
                    put("type",type);
                    put("value_type",value_type);
                    put("description",params.get("description").toString());
                    put("history",params.get("history").toString());
                    put("trends",params.get("trends").toString());
                }};
            }
            //创建snmp类型监控项
            else if(type == 1){
                allNewsForItem = new HashMap<String,Object>(){{
                    put("delay",params.get("delay").toString());
                    put("hostid",params.get("hostid").toString());
                    put("interfaceid",params.get("interfaceid").toString());
                    put("key_",params.get("key_").toString());
                    put("name",params.get("name").toString());
                    put("snmp_oid",params.get("snmp_oid").toString());
                    put("type",type);
                    put("value_type",value_type);
                    put("description",params.get("description").toString());
                    put("history",params.get("history").toString());
                    put("trends",params.get("trends").toString());
                }};
            }

            createFlag = itemService.creatMonitorItem(allNewsForItem,type);
        }

        boolean flag = (boolean) createFlag.get("flag");
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("log_objectName",params.get("name").toString());
         if (flag){
             responseMessage.setStatus(true);
             resultMap.put("createFlag","添加成功");
             resultMap.put("itemid",createFlag.get("message"));
             resultMap.put("log_description",params.get("key_").toString());
         }else{
             responseMessage.setStatus(false);
             resultMap.put("createFlag",createFlag.get("message"));
             responseMessage.setErrorCode("");
         }
        responseMessage.setContent(resultMap);
        return responseMessage;
    }
    /**
    * @Description //从XML文件中获取监控项key值
    * @Date 14:59 2020/12/8
    * @Param []
    **/
    @RequestMapping("/getItemKeyFromXML")
    public ResponseMessage getItemKey(@RequestParam(value = "hostId") String hostid,
                                      @RequestParam(value = "type") String type){
        ResponseMessage responseMessage = new ResponseMessage();
        //获取xml文件中的数据并进行封装
        Map<String, List<Map<String, Object>>> itemKeyFromXml = itemService.getItemKeyFromXml();
        List<Map<String, Object>> list;
        // 判断设备类型
        if (type.equals("1")){
            list = itemKeyFromXml.get("agent");
        }else {
            list = itemKeyFromXml.get("SNMP trap");
        }
        // 提取公共触发器键值，后进行匹配
        List<String> commonTrigger = new ArrayList<>();
        for (Map<String, Object> map : list) {
            String key = (String) map.get("key_");
            String[] split = key.split("\\[");
            commonTrigger.add(split[0]);
        }
        // 获取该设备所有触发器列表进行匹配
        List<Map<String, Object>> itemNews = itemService.getAllItem(hostid);
        HashMap<String, Integer> hashMap = new HashMap<>();
        for (Map<String, Object> itemNew : itemNews) {
            String key_ = (String) itemNew.get("key_");
            if (key_.contains("[")) {
                key_ = (String) key_.split("\\[")[0];
            }
            for (int i = 0; i < commonTrigger.size(); i++) {
                if (commonTrigger.get(i).equals(key_)){
                    hashMap.put(key_,hashMap.getOrDefault(key_, 0) + 1);
                }
            }
        }
        Map<String, Object> itemKeyMap = new HashMap<String, Object>() {{
            put("itemKeyMap",itemKeyFromXml);
            put("triggerNum", hashMap);
        }};
        responseMessage.setContent(itemKeyMap);
        responseMessage.setStatus(true);
        return responseMessage;
    }
}
